package other.xsy.paas;

import com.rkhd.platform.sdk.creekflow.autoflowevent.AutoFlowEvent;
import com.rkhd.platform.sdk.creekflow.autoflowevent.AutoFlowEventRequest;
import com.rkhd.platform.sdk.creekflow.autoflowevent.AutoFlowEventResponse;
import com.rkhd.platform.sdk.data.model.Contract;
import com.rkhd.platform.sdk.data.model.Order;
import com.rkhd.platform.sdk.data.model.OrderProduct;
import com.rkhd.platform.sdk.data.model.QuoteLine;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import other.xsy.paas.utils.HCXObjectService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 功能描述：自动流程调用此代码，判断是否有需要删除的订单明细
 *
 * @author whz
 * @ClassName: OrderProductTrigger
 * @Description:
 * @date 2024年03月23日
 */
public class ContractAutoFlowEvent implements AutoFlowEvent {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static Logger logger = LoggerFactory.getLogger();

    @Override
    public AutoFlowEventResponse execute(AutoFlowEventRequest request) {
        logger.error("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId() + " , ProcessInstanceId:" + request.getProcessInstanceId());
        logger.info(request.toString());
        AutoFlowEventResponse response = new AutoFlowEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        handler(request.getDataId());
        return response;
    }

    private void handler(Long contractId) {
        try {
            Contract contract = new Contract();
            contract.setId(contractId);
            contract = hcxObjectService.get(contract);
            logger.info("合同标题：" + contract.getTitle());
            String sql = "select id,po,contractId from _order where contractId = " + contractId + " and customItem210__c = 1";
            Order order = hcxObjectService.queryOne(sql);
            logger.info("订单编号：" + order.getPo());
            List<OrderProduct> orderProductList = queryOrderProductList(order.getId());
            if (orderProductList == null || orderProductList.size() <= 0) {
                logger.info("没有自动流程生成的订单明细");
                return;
            }
            List<QuoteLine> quoteLineList = queryQuoteLineList(contract.getOffer__c());
            if (quoteLineList == null || quoteLineList.size() <= 0) {
                logger.info("没有报价单明细");
                return;
            }
            List<OrderProduct> deleteList = new ArrayList<>();
            Map<Long, QuoteLine> quoteLineMap = quoteLineList.stream().collect(Collectors.toMap(QuoteLine::getId, o -> o));
            for (OrderProduct orderProduct : orderProductList) {
                QuoteLine quoteLine = quoteLineMap.get(orderProduct.getQuotationProject__c());
                if (quoteLine != null) {
                    continue;
                }
                deleteList.add(orderProduct);
            }
            logger.info("需要删除的订单明细数量：" + deleteList.size());
            hcxObjectService.batchDelete(deleteList);
        } catch (Exception e) {
            logger.error("系统异常：" + e.getMessage());
        }
    }

    private List<QuoteLine> queryQuoteLineList(Long quoteId) throws ApiEntityServiceException {
        String sql = "select id,name from quoteLine where quotationDetailEntityRelQuotationEntity = " + quoteId;
        List<QuoteLine> quoteLineList = (List<QuoteLine>) hcxObjectService.query(sql);
        return quoteLineList;
    }

    private List<OrderProduct> queryOrderProductList(Long orderId) throws ApiEntityServiceException {
        String sql = "select id,name,quotationProject__c from orderProduct where orderId = " + orderId + " and sequenceNumber__c = 1 and quotationProject__c is not null";
        List<OrderProduct> orderProductList = (List<OrderProduct>) hcxObjectService.query(sql);
        return orderProductList;
    }

}
